import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import viteCompression from 'vite-plugin-compression'
// import legacy from '@vitejs/plugin-legacy'
// import eslintPlugin from 'vite-plugin-eslint'
import { viteMockServe } from 'vite-plugin-mock'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { resolve } from 'path'
import eslintPlugin from './src/assets/vite-plugin-eslint/index.mjs'
// import qiankunCssPrefixPlugin from './vite-plugins/qiankun-auto-css-prefix.js'
import proxyConfig from './config/proxy.config'
import { DEV_ORIGIN } from './config/_vite_.config'

// const argvs = JSON.parse(process.env.npm_config_argv as any || {})?.original
// const RUN_PLAT = argvs[argvs.length - 1].replace('--', '')
/* eslint-disable */
export default defineConfig(({ mode }) => {
  // console.log('配置文件是：', loadEnv(mode, process.cwd()))
  const __IS_DEV__ = mode === 'development';  // 开发环境
  const __IS_PROD__ = mode === 'production';  // 生产环境（build:online)
  const baseConfig = {
    plugins: [
      vue(),
      vueJsx(),
      viteMockServe({ localEnabled: mode === 'mock' }),
      viteCompression({ //gzip静态资源压缩
        verbose: true,    // 默认即可
        disable: false,  //开启压缩(不禁用)，默认即可
        deleteOriginFile: false, // 删除源文件
        threshold: 10240, // 压缩前最小文件大小
        algorithm: 'gzip',  // 压缩算法
        ext: '.gz', //文件类型
      }),
      // legacy({
      //   targets: ['defaults', 'not IE 11'],
      //   renderLegacyChunks: false
      // }),
      eslintPlugin({
        include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue', 'src/**/*.ts'],
        cache: false
      }),
      // qiankunCssPrefixPlugin()
    ],
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less'],
      alias: {
        '@': resolve(__dirname, 'src'),
        '@public': resolve(__dirname, './public'),
        'element-plus/es/locale/lang/zh-cn': resolve(__dirname, './src/assets/locale/lang/zh-cn.js'),
        'element-plus': resolve(__dirname, './src/assets/element-plus/index.full.min.mjs'),
        '@plugins': resolve(__dirname, 'plugins'),
        '@config': resolve(__dirname, 'config'),
        '@global-config': resolve(__dirname, 'src/global-config'),
        '@views': resolve(__dirname, 'src/views'),
      },
    },
    esbuild: {
      drop: mode === 'production' ? ['console', 'debugger'] : []
    },
    build: {
     //浏览器兼容性  "esnext"|"modules"
     outDir: "dist",
     assetsDir: "assets",
     chunkSizeWarningLimit: 8000,
     cssCodeSplit: true,
     sourcemap: false,
     brotliSize: false, // 不统计
     minify: 'esbuild', // 混淆器，terser构建后文件体积更小
     rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              const arr = id.toString().split('node_modules/')[1].split('/')
              // if (arr[0].includes('vue')) {
              //   return '_' + arr[0]
              // } else if (arr[0].includes('lodash')) {
              //   return '_' + arr[0]
              // } else if (arr[0].includes('@amap')) {
              //   return '_' + arr[0]
              // } else if (arr[0].includes('query-string')) {
              //   return '_' + arr[0]
              // } else {
              //   return '__vendor'
              // }
              return '__vendor'
            }
            if (id.includes('element-plus')) {
              return '_' + 'element-plus'
            }
            if (id.includes('components')) {
              return '_' + 'components'
            } else if (id.includes('css') || id.includes('less')) {
              return '_' + 'pricss'
            }
          },
          chunkFileNames: 'static/local/[name]-[hash].js',
          entryFileNames: 'static/vendor/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
        }
     }
    },
    server: {
      open: true,
      proxy: proxyConfig('dev'),
      // host: DEV_ORIGIN.hostname,
      host: '0.0.0.0',
      port: ~~DEV_ORIGIN.port,
      origin: DEV_ORIGIN.origin,
      cors: {
        // credentials: true,
      },
    }
  }
  // if (__IS_PROD__) {
  //   Object.assign(baseConfig, {
  //     base: PORD_ORIGIN.origin + BASE_URL
  //   } as UserConfig)
  // }
  // else if (__IS_DEV__) {
  //   Object.assign(baseConfig, {
  //     base: DEV_ORIGIN.origin + BASE_URL,
  //   } as UserConfig)
  // } else {
  //   baseConfig.base = BASE_URL;
  // }
  return baseConfig
})
